﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model.ZSJL.com.Net;
using System.Net;
using System.IO;
using System.Web;
using System.Xml;

namespace Service.ZSJL.Com.Net
{
    public class LDSmsService : ISmsService
    {
        //<%@ Import Namespace= "System.Drawing"%> 联动天下短信 平台1.。已经作废
        // string SmsAPIUrl = "http://www.72dns.com/smsadmin/Sms_Api.aspx"; //页面提交地址
        // string SMSUser = "15"; //用户名ID
        //string SMSPassword = "E10ADC3949BA59ABBE56E057F20F883E"; //用户名密码 注:(从安全角度考虑请对密码进行MD5加密算法进行加密(格式为:32位加密,加密格式不区分大小写)) 可到http://tool.chinaz.com/Tools/MD5.aspx 进行加密处理

        // string SmsAPIUrl = "http://test.72dns.com/smsadmin/Sms_Api.aspx"; //页面提交地址
        //string SMSUser = "55"; //用户名ID
        //string SMSPassword = "E10ADC3949BA59ABBE56E057F20F883E"; //用户名密码 注:(从安全角度考虑请对密码进行MD5加密算法进行加密(格式为:32位加密,加密格式不区分大小写)) 可到http://tool.chinaz.com/Tools/MD5.aspx 进行加密处理



        //平台2  最土网，没有回复 功能 。

        //        http://notice.zuitu.com/sms?user=USERNAME&pass=PASSWORD&phones=PHONES&content=CONTENT

        //USERNAME：在本短信平台注册的用户名
        //PASSWORD：平台登录密码MD5后的值
        //PHONES：目标手机号码，多个手机号码使用半角逗号分隔，最多300个
        //CONTENT：发送内容，编码建议采用UTF-8
        //返回 '+OK' 视为发送成功，其他内容为错误提示内容
        private SmsConfig _smsConfig;
        /// <summary>
        /// 短信平台用户信息配置
        /// </summary>
        public SmsConfig SmsConfig
        {
            get { return _smsConfig; }
            set { _smsConfig = value; }
        }

        public LDSmsService()
        {
            //初始化默认配置
            Init();
        }

        private void Init()
        {
            this._smsConfig = new SmsConfig();


            _smsConfig.Password = "94C9F245C24843787770BF93D1208734";
            _smsConfig.SmsAPIUrl = "http://notice.zuitu.com/sms";
            _smsConfig.UserId = "djdnmq";


            //test
            // _smsConfig.SmsAPIUrl = "http://test.72dns.com/smsadmin/Sms_Api.aspx"; //页面提交地址
            // _smsConfig.UserId = "55"; //用户名ID
            // _smsConfig.Password= "E10ADC3949BA59ABBE56E057F20F883E
        }

        /// <summary>
        /// 传入配置
        /// </summary>
        /// <param name="smsConfig"></param>
        public LDSmsService(SmsConfig smsConfig)
        {
            this._smsConfig = smsConfig;


        }

        /// <summary>
        /// 内部操作类，获取短信回复内容
        /// </summary>
        /// <param name="pars"></param>
        /// <returns></returns>
        private List<SmsModel> SelectSmsAPI(string pars)
        {
            //string xml = SmsAPIUrl + SMSUser+"&PassWord="+SMSPassword+"&action=ReplySms";//获得文件的路径
            StringBuilder sb = new StringBuilder();
            List<SmsModel> ls = null;
            //string Datas = "&CrTime=2012-4-18"; //当输入日期(只是日期可以了，不用输入时间)时，为查询此日期前7天的回复内容;
            string Datas = pars;//CrTime为空时， 查询日期为当天前7天的回复内容;
            string xml = HttpGet("ReplySms", Datas, HttpAccessType.GET);
            if (xml.IndexOf("code=40") > -1 && xml.IndexOf("msg=") > -1) //调用出错时
            {
                sb.Append("<br>" + xml);

            }
            else
            {
                XmlDocument doc = new XmlDocument();
                xml = xml.Trim();
                doc.LoadXml(xml);
                XmlElement root = doc.DocumentElement;
                XmlNode child = doc.SelectSingleNode("/root/item ");
                if (child != null)
                {
                    XmlNodeReader reader = new XmlNodeReader(root);
                    ls = new List<SmsModel>();
                    SmsModel sms = null;
                    while (reader.Read())
                    {

                        if (reader.Name == "RepID")
                        {
                            sms = new SmsModel();
                            sms.Reid = reader.ReadString();
                            // sb.Append("<table border='1px' cellpadding='0' cellspacing='0'>");
                            //sb.Append("<tr><td>编号：</td><td>" + reader.ReadString() + "</td></tr>");
                        }
                        if (reader.Name == "CrTime")
                        {
                            // sb.Append("<tr><td>发信时间：</td><td>" + reader.ReadString() + "</td></tr>");
                            sms.CrTime = Convert.ToDateTime(reader.ReadString());
                        }
                        if (reader.Name == "SmsFrom")
                        {
                            sms.SmsFrom = reader.ReadString();
                            //sb.Append("<tr><td>发信人：</td><td>" + reader.ReadString() + "</td></tr>");
                        }
                        if (reader.Name == "SmsContent")
                        {

                            sms.Content = reader.ReadString();
                            // sb.Append("<tr><td>发信内容：</td><td>" + reader.ReadString() + "</td></tr>");
                        }
                        if (reader.Name == "Content")
                        {

                            sms.ReContent = reader.ReadString();
                            // sb.Append("<tr><td>回复内容：</td><td>" + reader.ReadString() + "</td></tr>");
                            //sb.Append("<table></br>");
                            ls.Add(sms);
                        }
                    }
                    reader.Close();//关闭XmlTextReader 
                }
            }
            //return HttpGet("Select", SmsAPIUrl);

            return ls;
        }

        private string HttpGet(string action, string Datas, HttpAccessType ac)
        {
            string ReUrl = "";
            string line = "";
            string param = "&UserID=" + SmsConfig.UserId + "&PassWord=" + SmsConfig.Password + "&action=" + action + Datas;
            byte[] bs = Encoding.ASCII.GetBytes(param);
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(SmsConfig.SmsAPIUrl);
            req.Method = ac.ToString();
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = bs.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
            }
            WebResponse wr = req.GetResponse();
            Stream strm = wr.GetResponseStream();
            StreamReader sr = new StreamReader(strm, System.Text.Encoding.Default);
            while ((line = sr.ReadLine()) != null)
            {
                ReUrl += line;
            }
            strm.Close();
            return ReUrl;
        }









        public string SendSmsAPI(SmsModel smsModel)
        {
            //Hashtable DataArry = new Hashtable();
            //DataArry["message"] = HttpUtility.UrlEncode(smsModel.Content, Encoding.GetEncoding("gb2312"));
            //DataArry["mobile"] = smsModel.PhoneNo;
            string Datas = "";
            //foreach (DictionaryEntry objDE in DataArry)
            //{
            Datas += "&" + "mobile" + "=" + smsModel.PhoneNo;
            Datas += "&" + "message" + "=" + HttpUtility.UrlEncode(smsModel.Content, Encoding.GetEncoding("gb2312"));
            //}
            return HttpGet("SendSms", Datas, HttpAccessType.GET);
        }

        public int CheckSumSms()
        {
            try
            {
                string ReUrl = "";
                ReUrl = HttpGet("CheckSumSms", ReUrl, HttpAccessType.GET);
                int start = ReUrl.IndexOf("sum=") + 4;
                int len = ReUrl.IndexOf("&msg") - start;
                ReUrl = ReUrl.Substring(start, len);
                return Convert.ToInt32(ReUrl);
            }
            catch (FormatException fex)
            {
                throw new Exception(fex.Message);
            }
        }






        #region ISMSService Members

        public List<SmsModel> GetReplySMSTable()
        {
            return SelectSmsAPI("");
        }

        public List<SmsModel> GetReplySMSTable(DateTime time)
        {
            try
            {
                return SelectSmsAPI("&CrTime=" + time.ToString("yyyy-MM-dd"));
            }
            catch (FormatException fex)
            {
                throw new Exception("时间格式不对，请传入正确日期时间." + fex.Message);

            }
        }


        #endregion


        public bool SendSms(SmsModel smsContent)
        {
            string result = SendSmsAPI(smsContent);
            if (result.IndexOf("code=200") > -1)
                return true;
            else
                throw new Exception(result);

        }
    }
}
